import jwt from 'jsonwebtoken';
import bcrypt from 'bcryptjs';
import { NextApiResponse } from 'next';
import dotenv from 'dotenv';
import { NextRequest, NextResponse } from 'next/server';
import { NextURL } from 'next/dist/server/web/next-url';

dotenv.config();

// const redis = new Redis({
//   port: parseInt(process.env.REDIS_PORT as string, 10),
//   host: process.env.REDIS_HOST,
//   password: process.env.REDIS_PASSWORD,
// });

interface DecodedToken {
  id: string;
  [key: string]: any;
}

// 扩展 NextApiRequest 接口
export interface ExtendedNextApiRequest extends NextRequest {
  user?: DecodedToken;
  geo: any;
  ip: string;
  nextUrl: NextURL;
}

// 生成 JWT 的函数，设置失效时间
export function generateToken(payload: object): string {
  const expiresIn = parseInt(process.env.JWT_EXPIRES_IN as string, 10);
  const sanitizedPayload = JSON.parse(JSON.stringify(payload, (key, value) =>
    typeof value === 'bigint' ? value.toString() : value
  ));
  return jwt.sign(sanitizedPayload, process.env.JWT_SECRET as string, { expiresIn });
}

// 密码加密函数
export async function hashPassword(password: string): Promise<string> {
  const saltRounds = 10;
  return await bcrypt.hash(password, saltRounds);
}

// 密码验证函数
export async function verifyPassword(password: string, hash: string): Promise<boolean> {
  return await bcrypt.compare(password, hash);
}

// 校验 JWT 是否超时
export function verifyToken(token: string): DecodedToken | null {
  try {
    return jwt.verify(token, process.env.JWT_SECRET as string) as DecodedToken;
  } catch (error) {
    if (error instanceof jwt.TokenExpiredError) {
      // console.log('Token expired');
    } else {
      // console.log('Token invalid');
    }
    return null;
  }
}
